<!--
 * @LastEditTime : 2022-10-31 15:06:57
 * @FilePath     : /pyy/src/components/PopupSelect/index.vue
 * @Description  : 公共组件 > 下拉选项(基于vant field\popup\picker 封装的弹出式下拉选择)
-->

<template>
  <div class="select">
    <van-field
      readonly
      clickable
      is-link
      arrow-direction="down"
      :label="label"
      :value="fieldValue"
      v-bind="$attrs"
      @click="show = true"
    />
    <van-popup v-model="show" position="bottom">
      <van-picker
        show-toolbar
        :columns="columns"
        :readonly="readonly"
        :title="label"
        @confirm="onConfirm"
        @cancel="show = false"
      />
    </van-popup>
  </div>
</template>

<script>
// 无数据时的 提示文本
const NO_DATA_TIP = "暂无数据";

export default {
  name: "PopupSelect",
  props: {
    value: String,
    label: String,
    selectLabel:String,
    options: {
      type: Array,
      require: true,
      default: () => [],
    },
    defaultSelect:{
      type: Object,
    },
    // 节点参数名
    defaultProps: {
      type: Object,
      default: () => ({
        label: "label",
        value: "value",
      }),
    },
  },
  model: {
    prop: "value",
    event: "update:value",
  },
  data() {
    return {
      show: false,
      selectValue: null,
    };
  },
  mounted(){
  },
  computed: {
    columns() {
      const result = this.options.map((item) => item[this.defaultProps.label]  );
      return result.length ? result : [NO_DATA_TIP];
    },
    readonly() {
      return this.columns[0] == NO_DATA_TIP;
    },
    fieldValue() {
      // 根据 value 回显 field展示文本
      const result = this.options.find(
        (item) => item[this.defaultProps.value] == this.value || item[this.defaultProps.label] == this.selectLabel 
      );
      return result ? result[this.defaultProps.label] : this.defaultSelect ? this.defaultSelect.name: "";
    },
  },
  methods: {
    /**
     * 点击 完成按钮
     * @param {any} value: 选中值
     * @param {number} index: 选中值对应的索引
     */
    onConfirm(value, index) {
      this.show = false;
      if (value == NO_DATA_TIP) return;

      const select = this.options[index];
      this.selectValue = select[this.defaultProps.value];
      this.$emit("update:value", this.selectValue);
    },
  },
};
</script>

<style lang="less" scoped></style>
